package com.yongqi.duocai.utils;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * 1.描述（@desc）：
 * 2.作者（@author）：夏亮辉
 * 3.日期（@date）：2021年06月30  21:43
 * 4.版本（@version）：1.0.0
 * 5.版权：
 */

public class HttpClientUtils {

    /**
     * 请求参数为 XML 格式的 Post 请求
     * @param url
     * @param requestDataXml
     * @return
     */
    public static String doPostByXml(String url, String requestDataXml){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;

        // 创建 httpClient 连接对象
        httpClient = HttpClients.createDefault();
        // 创建post 请求连接对象
        HttpPost httpPost = new HttpPost(url);
        // 创建连接请求参数对象，并设置连接参数
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(15000) // 连接服务器主机超时时间
                .setConnectionRequestTimeout(60000) // 连接请求超时时间
                .setSocketTimeout(60000) //设置读取响应数据超时时间
                .build();
        // 为 httpPost 请求设置参数
        httpPost.setConfig(requestConfig);

        // 将上传参数存放到 entity 属性中
        httpPost.setEntity(new StringEntity(requestDataXml, "UTF-8"));
        // 添加头信息
        httpPost.addHeader("Content-Type", "text/xml");

        String result = "";
        try{
            // 发送请求
            httpResponse = httpClient.execute(httpPost);
            // 从响应对象中获取内容
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity, "UTF-8");
        }catch (IOException e){
            e.printStackTrace();
        }
        return result;
    }

}
